home *** CD-ROM | disk | FTP | other *** search
/ Shareware Grab Bag / Shareware Grab Bag.iso / 007 / cstdio.arc / SRC.ARC / FGETS.C < prev    next >
C/C++ Source or Header  |  1984-07-31  |  548b  |  31 lines

  1. /*    fgets.c - get string from stream.
  2.     K & R page 155.
  3.     Entered - G. R. Mansfield.  84/06/08.
  4.     Ver 1.0-4731.
  5. */
  6.  
  7. #include <stdio.h>
  8.  
  9. char *fgets(s, n, fp)    /* get at most n characters from stream */
  10. char *s;
  11. int n;
  12. FILE *fp;
  13. {
  14.     int c;
  15.     char *cs;
  16.  
  17.     cs = s;
  18.     while (--n > 0 && (c = getc(fp)) != EOF) {
  19.         if ((*cs++ = c) == '\n')
  20.             break;
  21.     }
  22.     if (cs - s >= 2) {    /* delete possible CR from end of line */
  23.         if (*(cs-2) == '\r') {
  24.             cs--;
  25.             *(cs-1) = '\n';
  26.         }
  27.     }
  28.     *cs = '\0';
  29.     return((c == EOF && cs == s) ? NULL : s);
  30. }
  31.